<template>
    <div class="group-box">
        <template class="chat-message" v-for="message in grouplist">
            <el-col :span="18" :offset="4">
                <div :style="stylechange(message.chat.username)" class="message-content">
                    <p class=msgdate>{{ message.chat.msg_date }}</p>
                    <div>{{ message.chat.msg }}</div>
                </div>
            </el-col>
        </template>
        <el-input
                placeholder="请输入内容"
                v-model="input"
                clearable class="inputl">
        </el-input>
        <el-button type="info" plain @click="MsgClick(input)">发送</el-button>
    </div>
</template>

<script>
    import axios from "axios";

    export default {
        name: "group",
        data() {
            return {
                grouplist: [],
                input: '',
                username: '',
            }
        },
        created() {
            // 在组件创建时启动定时执行
            this.intervalId = setInterval(this.groupMethod, 1000);
        },
        beforeDestroy() {
            // 在组件销毁前清除定时器
            clearInterval(this.intervalId);
        },
        methods: {
            MsgClick(msg) {
                axios.post('http://127.0.0.1:8000/api/groupchatmsg/', {
                    'username': this.username,
                    'groupname': this.groupmsg,
                    'msg': msg,
                }, {
                    headers: {
                        token: sessionStorage.getItem('token'),
                    },
                })
                this.input=''
            },
            stylechange(name) {
                if (name == this.username) {
                    return ' float: right;'
                } else {
                    return ' float: left;'
                }
            },
            groupMethod() {
                console.log(this.groupmsg)
                axios.get('http://127.0.0.1:8000/api/groupchatmessage/', {
                        headers: {
                            token: sessionStorage.getItem('token')
                        },
                        params: {
                            groupname: this.groupmsg
                        }
                    }
                ).then(res => {
                    console.log(res.data.results)
                    this.grouplist = res.data.results
                    this.username = sessionStorage.getItem('username')
                })
                    .catch(error => {
                        console.log(error);
                    });

            }
        }
        ,
        props: ['groupmsg'],


    }
</script>

<style scoped>
    .message-content {
        float: left;
        background-color: #f2f2f2;
        border-radius: 8px;
        padding: 10px;
        margin-bottom: 10px;
        width: 40%;
    }

    .msgdate {
        float: left;
        width: 100%;
    }

    .inputl {
        width: 50%;
    }
</style>